package com.bishe.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.bishe.entity.FileInfo;
import com.bishe.entity.response.R;
import com.bishe.service.FileService;
import com.bishe.util.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import kotlin.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件控制器
 */


@RestController
@RequestMapping("file")
@Api(tags = "文件控制层")
public class FileController {

    @Resource
    private FileService fileService;

    @SaIgnore
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public R<?> upload(MultipartFile file) {
        return R.ok("上传成功",fileService.upload(file));
    }


    @SaIgnore
    @ApiOperation("下载文件")
    @GetMapping("/download/{fileId}")
    public R<?> download(@PathVariable String fileId, HttpServletResponse response) {
        FileInfo fileInfo = fileService.getById(fileId);
        FileUtils.download(response, FileUtils.getFile(fileInfo));
        return R.ok();
    }


    @SaIgnore
    @ApiOperation("删除文件")
    @DeleteMapping("/deleteFile/{fileId}")
    public R<?> deleteFile(@PathVariable String fileId) {
        fileService.deleteFile(fileId);
        return R.ok();
    }


    @SaIgnore
    @ApiOperation("根据业务id获取文件")
    @GetMapping("/getById/{id}")
    public R<FileInfo> getByDateId(@PathVariable String id) {
        FileInfo byId = fileService.getByDateId(id);
        return R.ok("ok", byId);
    }

    @SaIgnore
    @ApiOperation("获取头像")
    @GetMapping("/getPhoto/{id}")
    public R<?> getPhoto(HttpServletResponse response, @PathVariable String id) {
        FileInfo fileInfo = fileService.getByDateId(id);
        if (fileInfo != null) {
            FileUtils.download(response, FileUtils.getFile(fileInfo));
            return R.ok();
        }
        return null;
    }


}
